//
//  Task.m
//  TaskManager
//
//  Created by Dmitriy on 31.05.13.
//  Copyright (c) 2013 __MyCompanyName__. All rights reserved.
//

#import "Task.h"

@implementation Task
@synthesize taskTime = _taskTime;
@synthesize taskName = _taskName;
@synthesize notificationInterval=_notificationInterval;

-(void)toggleNotification
{
    if (notification==nil) {
        notification = [[UILocalNotification alloc] init];
        [notification setFireDate:[self.taskTime dateByAddingTimeInterval: -_notificationInterval]];
        [notification setAlertBody:self.taskName];
        [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    }
    else 
    {
        [[UIApplication sharedApplication] cancelLocalNotification:notification];
        [notification release];
        notification = nil;
    }
}

-(BOOL) hasNotification
{
    return notification!=nil;
}

-(id)init
{
    self = [[Task alloc] initWithName:nil time:nil];

    return self;
}
-(void) dealloc
{
    [_taskName release];
    [_taskTime release];
    [super dealloc];
}

-(id)initWithName:(NSString *)name
             time:(NSDate*)time
{
    self = [super init];
    if(self)
    {
        _taskTime = [time copy];
        _taskName = [name copy];
        notification = nil;
        _notificationInterval = -1;
    }
    return self;
}
-(void)modifyWithName:(NSString*)name 
             WithTime:(NSDate*)time
{
    self.taskName = nil;
    self.taskTime = nil;
    _taskTime = [time copy];
    _taskName = [name copy];
}
-(NSDate*) notificationTime
{
    return [self.taskTime dateByAddingTimeInterval:-_notificationInterval];
}

#pragma mark NSCoding

-(id) initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    if(self)
    {
        _taskName = [aDecoder decodeObjectForKey:@"TaskName"];
        _taskTime = [aDecoder decodeObjectForKey:@"TaskTime"];
        _notificationInterval = [aDecoder decodeDoubleForKey:@"NotificationInterval"];
    }
    return self;
}

-(void) encodeWithCoder:(NSCoder *)aCoder
{
     [aCoder encodeObject:_taskName forKey:@"TaskName"];
     [aCoder encodeObject:_taskTime forKey:@"TaskTime"];
     [aCoder encodeDouble:_notificationInterval forKey:@"NotificationInterval"];
}

@end
